package cn.linjianhui.thread;

import lombok.Getter;
import lombok.Setter;

public class StopThreadUnsafe {
    public static User u = new User();

    @Getter
    @Setter
    public static class User {
        private int id;
        private String name;

        public User() {
            id = 0;
            name = "0";
        }

        public String toString() {
            return "User [id=" + id + ", name=" + name + "]";
        }
    }

    public static class ChangeObjectThread extends Thread {

        @Override
        public void run() {
            while (true) {
                if(Thread.currentThread().isInterrupted()) {
                    System.out.println("Interrupted!");
                    break;
                }
                synchronized(u) {
                    int v = (int)(System.currentTimeMillis() / 1000);
                    u.setId(v);

                    // 做其他业务逻辑，模拟执行时间
                    try{
                        Thread.sleep(100);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                        // sleep方法由于中断而抛出异常，此时，它会清除中断标志，所以重新设置标志位
                        Thread.currentThread().interrupt();
                    }

                    u.setName(String.valueOf(v));
                }
                Thread.yield();
            }
        }
    }

    public static class ReadObjectThread extends Thread {

        @Override
        public void run() {
            while (true) {
                synchronized (u) {
                    if(u.getId() != Integer.parseInt(u.getName())) {
                        System.out.println(u.toString());
                    }
                }
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ReadObjectThread().start();
        while(true) {
            Thread t = new ChangeObjectThread();
            t.start();
            Thread.sleep(150);
            t.interrupt();
        }
    }
}
